﻿using Kingdee.BOS;
using Kingdee.BOS.Log;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.Log;
using Kingdee.BOS.Orm;
using Kingdee.BOS.ServiceHelper;
using Newtonsoft.Json;
using RK.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.MySchedule.BPW
{
    //2、开发一个定时任务，检查销售订单数量=累出库数量，且最后一次销售出库单的日期大于70的，进行业务关闭；
    public class AutoCloseSalOrder : IScheduleService
    {
        private Context context;
        public void Run(Context ctx, Schedule schedule)
        {
            this.context = ctx;
            context.CurrentOrganizationInfo.ID = 1;
            //李经理账号
            context.UserId = 100069;
            //查出所有累计出库大于等于订单数量，且未业务关闭的行，并且最后一次销售出库日期已经过去70天的行，进行自动业务关闭
            string seleSql = @"
            SELECT T0.FID, 
                   T1.FENTRYID
            FROM T_SAL_ORDER T0
                 JOIN T_SAL_ORDERENTRY T1 ON T1.FID = T0.FID
                 JOIN T_SAL_ORDERENTRY_R T2 ON T2.FENTRYID = T1.FENTRYID
                 LEFT JOIN
            (
                SELECT T0.FSID, 
                       MAX(T4.FDATE) FDATE
                FROM T_SAL_DELIVERYNOTICEENTRY_LK T0
                     JOIN T_SAL_DELIVERYNOTICEENTRY T1 ON T1.FENTRYID = T0.FENTRYID
                     JOIN T_SAL_OUTSTOCKENTRY_LK T2 ON T2.FSID = T1.FENTRYID
                                                       AND T2.FSTABLENAME = 'T_SAL_DELIVERYNOTICEENTRY'
                     JOIN T_SAL_OUTSTOCKENTRY T3 ON T3.FENTRYID = T2.FENTRYID
                     JOIN T_SAL_OUTSTOCK T4 ON T4.FID = T3.FID
                WHERE T0.FSTABLENAME = 'T_SAL_ORDERENTRY'
                GROUP BY T0.FSID
            ) T3 ON T3.FSID = T1.FENTRYID
            WHERE 1 = 1
                  AND T1.FMrpCloseStatus = 'A'
                  AND T0.FDOCUMENTSTATUS = 'C'
                  AND T0.FCloseStatus = 'A'
                  AND T2.FStockOutQty >= T1.FQty
                  AND CONVERT(INT, GETDATE()-ISNULL(T3.FDATE, GETDATE())  ) >= 70";
            var dynObjs = DBUtils.ExecuteDynamicObject(context, seleSql);
            Logger.Info("销售订单自动业务关闭", $"共{dynObjs.Count.ToString()}行符合关闭条件");
            try
            {
                var blInfo = FormMetaDataCache.GetCachedFormMetaData(ctx, "SAL_SaleOrder ").BusinessInfo;
                if (dynObjs.Count > 0)
                {
                    var logs = new List<LogObject>();
                    foreach (var dynObj in dynObjs)
                    {
                        List<KeyValuePair<object, object>> pkEntryIds = new List<KeyValuePair<object, object>>();
                        KeyValuePair<object, object> item = new KeyValuePair<object, object>(dynObj[0], dynObj[1]);
                        pkEntryIds.Add(item);
                        //var pkEntryIds = new List<KeyValuePair<object, object>>(new[] { new KeyValuePair<object, object>(dynObj[0], dynObj[1]) });
                        var res = BusinessDataServiceHelper.SetBillStatus(context, blInfo, pkEntryIds, null, "YLMRPClose");
                        string errs = JsonConvert.SerializeObject(res.ValidationErrors.Select(s => s.Message).ToList());
                        Logger.Info("销售订单自动业务关闭", res.IsSuccess.ToString() + "_" + errs);
                        var log = new LogObject();
                        log.pkValue = dynObj[1].ToString();
                        log.Description = JsonConvert.SerializeObject(res);
                        log.OperateName = "销售订单自动业务关闭";
                        log.ObjectTypeId = blInfo.GetForm().Id;
                        log.SubSystemId = blInfo.GetForm().SubsysId;
                        log.Environment = OperatingEnvironment.BizOperate;
                        logs.Add(log);
                    }
                    LogServiceHelper.BatchWriteLog(context, logs);
                }
            }
            catch (KDException ex)
            {
                Logger.Info($"销售订单自动业务关闭", $"报错原因1：{ex.Message}");
            }
            catch (Exception ex)
            {
                Logger.Info($"销售订单自动业务关闭", $"报错原因2：{ex.Message}");
            }
        }
    }
}